package com.helen.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.helen.entity.generator.DataGenerator;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.utils.MyLog;
import com.helen.utils.tiputils.MToast;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;

import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity implements TabHost.OnTabChangeListener {
    private Fragment[] mFragments;
    private FragmentTabHost mTabHost;
    private long exitTime = 0;
    private RxPermissions rxPermissions;
    private File tempFile = new File(Environment.getExternalStorageDirectory() + Constants.GLIDE_CARCH_DIR);
    public static boolean isForeground = false;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        rxPermissions = new RxPermissions(MainActivity.this);
        getPermissions();
        mFragments = DataGenerator.getFragments();
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        // 关联TabHost
        mTabHost.setup(this, getSupportFragmentManager(), R.id.home_container);
        //注意，监听要设置在添加Tab之前
        mTabHost.setOnTabChangedListener(this);

        //添加Tab
        for (int i = 0; i < 4; i++) {
            //生成TabSpec
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(DataGenerator.mTabTitle[i]).setIndicator(DataGenerator.getTabView(this, i));
            // 添加Tab 到TabHost，并绑定Fragment
            Bundle bundle = new Bundle();
//            bundle.putString("from", "FragmentTabHost Tab");
            mTabHost.addTab(tabSpec, mFragments[i].getClass(), bundle);
        }


        //去掉Tab 之间的分割线
        mTabHost.getTabWidget().setDividerDrawable(null);
        mTabHost.setCurrentTab(0);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onTabChanged(String tabId) {
        switch (tabId) {
            case "消息":
            case "购物车":
            case "我的":
                if (!checkLoginState()) {
                    if (mTabHost != null) {
                        mTabHost.setCurrentTab(0);
                    }
                    return;
                }
                break;
        }
        updateTabState();
    }



    /**
     * 更新Tab 的状态
     */
    private void updateTabState() {
        TabWidget tabWidget = mTabHost.getTabWidget();
        for (int i = 0; i < tabWidget.getTabCount(); i++) {
            View view = tabWidget.getChildTabViewAt(i);
            ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_image);
            TextView tabText = (TextView) view.findViewById(R.id.tab_title);
            if (i == mTabHost.getCurrentTab()) {
                tabIcon.setImageResource(DataGenerator.mTabResPressed[i]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeColor));
            } else {
                tabIcon.setImageResource(DataGenerator.mTabRes[i]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeTitleColor));
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                MToast.makeTextShort(MainActivity.this, "再按一次退出应用", toastConfig).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }





    public void getPermissions() {
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            if (!tempFile.exists()) {
                                tempFile.mkdirs();
                            }
                        } else {
                            showMissingPermissionDialog();
                        }
                    }
                });
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。\n请点击设置->权限->打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
                    }
                });

        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        MyLog.e("yang","isForeground==="+isForeground);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isForeground = false;
        MyLog.e("yang","isForeground==="+isForeground);
    }
}
